<?php
class VocabularyController extends Controller{
	function __construct(){
		parent::__construct();
		$this->taxonomyAction = new TaxonomyAction();
	}
	
	function index(){
	    $machine_name = trim($_GET['mn']);
	    $vocabulary = $this->taxonomyAction->getVocabularyByMachineName($machine_name);
	    $_SESSION['vid'] = $vocabulary['vid'];
		$this->smarty->display('admin/vocabulary/index.tpl');
	}
	
	function term_list(){
	    $vid = $_SESSION['vid'];
	    $tree = $this->taxonomyAction->termTree($vid);
	    
	    $this->smarty->assign('tree', $tree);
	    $this->smarty->display('admin/vocabulary/term_list.tpl');
	}
	
	function edit_submit(){
	    $tid = $_POST['id'];
	    $name = trim($_POST['value']);
	    
	    $this->taxonomyAction->termUpdate(array('tid' => $tid, 'name' => $name));
	    echo $name;
	}
	function edit_weight(){
	    $tid = $_POST['id'];
	    $weight = intval($_POST['value']);
	     
	    $this->taxonomyAction->termUpdate(array('tid' => $tid, 'weight' => $weight));
	    echo $weight;
	}
	function term_add(){
		$vid = $_SESSION['vid'];

		$vac = $vid? $this->taxonomyAction->vocabularyGetOne($vid): null;
		$terms = $vac? $this->taxonomyAction->termList($vac['vid']): null;
		
		$this->smarty->assign('vac', $vac);
		$this->smarty->assign('terms', $terms);
		$this->smarty->display('admin/vocabulary/term_add.tpl');
	}
	
	function term_submit(){
		$fields = array(
			'name' => '名称不能为空',
			'vid' => '请选择分类',
		);
		$cp = check_post(array_keys($fields));
		if(!($cp === '1')){
			exit($fields[$cp]);
		}
		
		$result = $this->taxonomyAction->termAdd($_POST);
		switch ($result){
			case 1:
				$msg = 'success';
				break;
			case -1:
				$msg = '添加失败';
				break;
			default:
				$msg = '未知的错误';
		}
		exit($msg);
		
	}
	
	
	
	function term_delete(){
		$tid = intval($_POST['tid']);
		if($tid){
			$result = $this->taxonomyAction->termDel($tid);
			exit("$result");
		}else{
			exit('-3');
		}
	}
	
	function get_child_terms_options_html(){
		$parent = intval($_POST['parent']);
		$term = $this->taxonomyAction->getTerm($parent);
		$terms = $this->taxonomyAction->termList($term['vid'], $term['tid']);
		$html = '';
		foreach($terms as $t){
			$html .= "<option value=\"{$t['tid']}\">{$t['name']}</option>";
		}
		exit($html);
	}
}